from fastapi import APIRouter, Depends
from app.db.crud.user_crud import get_user, register_user, del_user, update_user
from app.db.crud import get_db
from sqlalchemy.orm import Session
from app.api.schemas.user import UserDataBase, UserBase
from typing import Optional, Union
from app.common.response_code import resp_200, resp_400
from app.common.security import check_jwt_token


# 实例化API路由，需注册到主路由上去
userAdminAPI = APIRouter(dependencies=[Depends(check_jwt_token)])


# 注册新用户API
@userAdminAPI.post("/register", summary="注册用户接口")
async def register(user: UserDataBase, db: Session = Depends(get_db)):
    if(get_user(db, user.userName)):
        return resp_400(user, message="用户已存在")
    else:
        return resp_200([UserBase(**user.dict()) for user in register_user(db, user)], message="新用户注册成功")


# 查询用户API
@userAdminAPI.post("/getuser", summary="用户查询接口")
async def getUser(user: Optional[UserBase] = None, db: Session = Depends(get_db)):
    return resp_200([UserBase(**user.dict()) for user in get_user(db, user.userName)])

# 更新用户API
@userAdminAPI.post("/updateuser", summary="更新用户接口")
async def updateuser(user: UserBase, db: Session = Depends(get_db)):
    return resp_200([UserBase(**user.dict()) for user in update_user(db, user)], message='更新成功')

# 删除用户API
@userAdminAPI.post("/deleteuser", summary="删除用户接口")
async def deleteuser(user: UserBase, db: Session = Depends(get_db)):
    return resp_200([UserBase(**user.dict()) for user in del_user(db, user.userName)], message="删除用户成功")
